package com.rongke.web.controller.medical;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.biz.service.MedicalRecordManager;
import com.rongke.commons.JsonResp;
import com.rongke.enums.MedicalRecordStatusEnum;
import com.rongke.model.MedicalAdvice;
import com.rongke.model.MedicalRecords;
import com.rongke.model.UserAuthorizeRecord;
import com.rongke.service.MedicalAdviceService;
import com.rongke.service.MedicalRecordsService;
import com.rongke.service.UserAuthorizeRecordService;
import com.rongke.utils.StringUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 病历管理大controller
 * 
 * @MedicalRecordsController
 * @病历Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/medicalRecords")
@Transactional
public class MedicalRecordsController {
	private static final Logger log = Logger
			.getLogger(MedicalRecordsController.class);

	@Autowired
	private MedicalRecordsService medicalRecordsService;

	@Autowired
	private MedicalRecordManager medicalRecordManager;

	@Autowired
	private UserAuthorizeRecordService userAuthorizeRecordService;

	@Autowired
	private MedicalAdviceService medicalAdviceService;

	/**
	 * 根据登陆者ID查询病历基本信息
	 * 
	 * @param medicalRecords
	 * @return
	 */
	@RequestMapping(value = "/queryByUser", method = RequestMethod.GET)
	public JsonResp queryByUserId(String userId) {
		log.debug("queryByUserId");

		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("user_id", userId);
			List<MedicalRecords> medicalRecords = medicalRecordsService
					.selectByMap(param);
			if (CollectionUtils.isEmpty(medicalRecords)) {
				return JsonResp.ok();
			} else {
				return JsonResp.ok(medicalRecords.get(0));
			}
		} catch (Exception e) {
			log.error("queryByUserId failed", e);
			return JsonResp.fa(null);
		}
	}

	/**
	 * 根据登陆者ID查询病历基本信息
	 * 
	 * @param medicalRecords
	 * @return
	 */
	@RequestMapping(value = "/queryById", method = RequestMethod.GET)
	public JsonResp queryById(String medicalRecordId) {
		log.debug("queryById");

		try {
			MedicalRecords medicalRecord = medicalRecordsService
					.selectById(medicalRecordId);
			return JsonResp.ok(medicalRecord);

		} catch (Exception e) {
			log.error("queryById failed", e);
			return JsonResp.fa(null);
		}
	}

	@RequestMapping(value = "/savePatientInfo", method = RequestMethod.POST)
	public JsonResp savePatientInfo(@RequestBody MedicalRecords medicalRecords) {
		log.debug("savePatientInfo");

		try {
			String userId = medicalRecords.getUserId();
			if (StringUtil.isEmpty(userId)) {
				log.error("get null userId in savePatientInfo");
				return JsonResp.fa(null);
			}

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("user_id", userId);
			List<MedicalRecords> medicalRecordList = medicalRecordsService
					.selectByMap(param);

			// 第一个步骤里只有几个参数，其他参数忽略
			MedicalRecords medicalDo = new MedicalRecords();
			medicalDo.setName(medicalRecords.getName());
			medicalDo.setIdCard(medicalRecords.getIdCard());
			medicalDo.setAddress(medicalRecords.getAddress());
			medicalDo.setSex(medicalRecords.getSex());
			medicalDo.setAge(medicalRecords.getAge());
			medicalDo.setHeight(medicalRecords.getHeight());
			medicalDo.setWeight(medicalRecords.getWeight());

			if (CollectionUtils.isEmpty(medicalRecordList)) {
				// 当前用户下没有病历，直接新增

				medicalDo.setUserId(medicalRecords.getUserId());
				medicalRecordsService.insert(medicalDo);

				JSONObject json = new JSONObject();
				json.put("id", medicalDo.getId());
				return JsonResp.ok(json);
			} else {
				medicalDo.setId(medicalRecordList.get(0).getId());
				medicalRecordsService.updateById(medicalDo);
			}

			JSONObject json = new JSONObject();
			json.put("id", medicalDo.getId());
			return JsonResp.ok(json);

		} catch (Exception e) {
			log.error("savePatientInfo failed", e);
			return JsonResp.fa(null);
		}
	}

	@RequestMapping(value = "/saveCancerType", method = RequestMethod.POST)
	public JsonResp saveCancerType(@RequestBody MedicalRecords medicalRecords) {
		log.debug("saveCancerType");

		try {
			// 直接修改癌症类型即可
			MedicalRecords medicalDo = new MedicalRecords();
			medicalDo.setId(medicalRecords.getId());
			medicalDo.setCancerTypeId(medicalRecords.getCancerTypeId());
			medicalRecordsService.updateById(medicalDo);

			JSONObject json = new JSONObject();
			json.put("id", medicalDo.getId());
			return JsonResp.ok(json);

		} catch (Exception e) {
			log.error("saveCancerType failed", e);
			return JsonResp.fa(null);
		}
	}

	@RequestMapping(value = "/saveCancerInfo", method = RequestMethod.POST)
	public JsonResp saveCancerInfo(@RequestBody MedicalRecords medicalRecords) {
		log.debug("saveCancerInfo");

		try {
			// 癌症的详细信息
			MedicalRecords medicalDo = new MedicalRecords();
			medicalDo.setId(medicalRecords.getId());
			medicalDo.setStaging(medicalRecords.getStaging());
			medicalDo.setTreatmentDate(medicalRecords.getTreatmentDate());
			medicalDo.setTreatmentHospital(medicalRecords
					.getTreatmentHospital());
			medicalDo.setTreatmentDoctor(medicalRecords.getTreatmentDoctor());

			medicalRecordsService.updateById(medicalDo);

			JSONObject json = new JSONObject();
			json.put("id", medicalDo.getId());
			return JsonResp.ok(json);

		} catch (Exception e) {
			log.error("saveCancerInfo failed", e);
			return JsonResp.fa(null);
		}
	}

	/**
	 * 点击“生成我的精准治疗建议”按钮
	 */
	@RequestMapping(value = "/generateAdvice", method = RequestMethod.POST)
	public JsonResp generateAdvice(long medicalRecordId) {
		try {
			log.debug("generateAdvice");

			// TODO:调用后台决策接口，生成未审核的决策建议
			MedicalRecords medicalDo = new MedicalRecords();
			medicalDo.setId(medicalRecordId);
			medicalDo.setStatus(1);// 治疗建议正在等待专家审核
			medicalRecordsService.updateById(medicalDo);

			JSONObject json = new JSONObject();
			json.put("medicalRecordId", medicalDo.getId());
			return JsonResp.ok(json);
		} catch (Exception e) {
			log.error("generateAdvice failed", e);
			return JsonResp.fa(null);
		}
	}

	/**
	 * 根据病历ID，生成时间轴
	 * 
	 * @param medicalRecordId
	 * @return
	 */
	@RequestMapping(value = "/getTimeLine", method = RequestMethod.GET)
	public JsonResp getTimeLine(long medicalRecordId) {
		try {
			log.debug("getTimeLine");

			List<JSONObject> totalRecordList = medicalRecordManager
					.getDetailTimeline(medicalRecordId);
			return JsonResp.ok(totalRecordList);

		} catch (Exception e) {
			log.error("getTimeLine failed", e);
			return JsonResp.fa(null);
		}
	}

	/**
	 * 患者点击"完成病历"，病历添加/修改结束
	 * 
	 * @param medicalRecordId
	 * @return
	 */
	@RequestMapping(value = "/finish", method = RequestMethod.POST)
	public JsonResp finishMedicalRecord(HttpServletRequest request,
			long medicalRecordId) {
		log.debug("finishMedicalRecord, medicalRecordId=" + medicalRecordId);
		try {
			String userId = (String) request.getSession()
					.getAttribute("userId");
			if (StringUtil.isEmpty(userId)) {
				log.info("get userId from session failed");
				return JsonResp.fa(null);
			}

			// 每次用户点击“完成病历”，都为当前病历生成一个新的advice，但是内容为空。
			// 目的是避免用户修改病例/专家审核建议 中间出现的并发
			MedicalAdvice adviceDo = new MedicalAdvice();
			adviceDo.setMedicalRecordId(medicalRecordId);
			medicalAdviceService.insert(adviceDo);

			MedicalRecords medicalRecordDo = new MedicalRecords();
			medicalRecordDo.setId(medicalRecordId);
			// 查询授权情况
			EntityWrapper<UserAuthorizeRecord> ew = new EntityWrapper<UserAuthorizeRecord>();
			ew.eq("medical_record_id", medicalRecordId);
			ew.eq("user_id", userId);
			int count = userAuthorizeRecordService.selectCount(ew);
			if (count > 0) {
				// 病历状态修改成2（病历已经修改，正在等待专家审核）
				medicalRecordDo.setStatus(MedicalRecordStatusEnum.MODIFIED
						.getStatus());
			} else {
				// 从未授权过，病历状态是1
				medicalRecordDo.setStatus(MedicalRecordStatusEnum.AUTHORIZE
						.getStatus());
			}
			medicalRecordsService.updateById(medicalRecordDo);

			JSONObject result = new JSONObject();
			result.put("medicalRecordId", medicalRecordId);
			return JsonResp.ok(result);
		} catch (Exception e) {
			log.error("finishMedicalRecord failed, medicalRecordId="
					+ medicalRecordId, e);
			return JsonResp.fa(null);
		}
	}
}
